#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

const int basesize = 1024;
const int argvnum = 64;

char *gargv[argvnum];
int gargc=0;


string GetUserName()
{
    string name = getenv("USER");
    return name.empty() ? "None" : name;
}

string GetHostName()
{
    string hostname = getenv("HOSTNAME");
    return hostname.empty() ? "None" : hostname;
}

string GetPwd()
{
    string pwd = getenv("PWD");
    return pwd.empty() ? "None" : pwd;
}

string MakeCommandLine()
{
    char command_line[basesize];
    snprintf(command_line, basesize, "[%s@%s %s]# ",\
        GetUserName().c_str(), GetHostName().c_str(), GetPwd().c_str());
    return command_line;
}

void PrintCommandLine() // 1. 命令行提示符
{
    printf("%s", MakeCommandLine().c_str());
    fflush(stdout);
}



bool GetCommandLine(char command_buffer[], int size)   // 2. 获取用户命令
{
    char *result = fgets(command_buffer, size, stdin);
    if(!result)
    {
        return false;
    }
    command_buffer[strlen(command_buffer)-1] = 0;
    if(strlen(command_buffer) == 0) return false;
    return true;
}



void ParseCommandLine(char command_buffer[], int len) // 3. 分析命令
{
    (void)len;
    memset(gargv, 0, sizeof(gargv));
    gargc = 0;
  
    const char *sep = " ";
    gargv[gargc++] = strtok(command_buffer, sep);
    
    while((bool)(gargv[gargc++] = strtok(nullptr, sep)));
    gargc--;
}

void debug()
{
    printf("argc: %d\n", gargc);
    for(int i = 0; gargv[i]; i++)
    {
        printf("argv[%d]: %s\n", i, gargv[i]);
    }
}



bool ExecuteCommand()
{
    pid_t id=fork();
    if(id<0) return false;

    if(id == 0)
    {
        //子进程执行
        execvp(gargv[0],gargv);

        exit(1);
    }

    int status=0;
    pid_t rid=waitpid(id,&status,0);
    if(rid>0)
    {
        
      return true;
    }
    return false;
}


int main()
{
    char command_buffer[basesize];
    while(true)
    {
        // 1. 命令行提示符
        PrintCommandLine(); 
       
        // 2. 获取用户命令 
        if(!GetCommandLine(command_buffer, basesize)) 
        {
            continue;
        }
        //printf("%s\n",command_buffer);

        // 3. 分析命令
        ParseCommandLine(command_buffer, strlen(command_buffer));
        //debug();
        
        // 4. 执行命令
        ExecuteCommand();



    }
    return 0;
}
